<?php

namespace app\index\controller;

use app\common\model\ArticleModel;
use app\common\model\FruitModel;
use app\common\model\MemberModel;
use app\common\model\RequirementModel;
use app\common\model\RequirementTypeModel;
use app\common\model\SlideModel;
use app\common\model\TeacherModel;
use app\index\validate\Requirement;
use think\Db;

class RequirementController extends BaseController
{
    public function index()
    {
        $keyword = $this->request->param('keyword');
        $college_id = $this->request->param('college_id');
        $page = $this->request->param('page') ? $this->request->param('page') : 1;



        if ($keyword){
            if ($college_id){
                $count = RequirementModel::where('status', 1)
                    ->where('college',$college_id)
                    ->where('title','like','%'.$keyword.'%')
                    ->whereOr('content','like','%'.$keyword.'%')
                    ->count();
                if (is_mobile()){
                    $requirements = RequirementModel::with(['requirement_type', 'teacher', 'member'])
                        ->where('status', 1)
                        ->where('college',$college_id)
                        ->where('title','like','%'.$keyword.'%')
                        ->whereOr('content','like','%'.$keyword.'%')
                        ->order('create_time desc')
                        ->all();
                }else{
                    $requirements = RequirementModel::with(['requirement_type', 'teacher', 'member'])
                        ->where('status', 1)
                        ->where('college',$college_id)
                        ->where('title','like','%'.$keyword.'%')
                        ->whereOr('content','like','%'.$keyword.'%')
                        ->order('create_time desc')
                        ->page($page, 10)
                        ->all();
                }
            }else{
                $count = RequirementModel::where('status', 1)
                    ->where('title','like','%'.$keyword.'%')
                    ->whereOr('content','like','%'.$keyword.'%')
                    ->count();
                if (is_mobile()){
                    $requirements = RequirementModel::with(['requirement_type', 'teacher', 'member'])
                        ->where('status', 1)
                        ->where('title','like','%'.$keyword.'%')
                        ->whereOr('content','like','%'.$keyword.'%')
                        ->order('create_time desc')
                        ->all();
                }else{
                    $requirements = RequirementModel::with(['requirement_type', 'teacher', 'member'])
                        ->where('status', 1)
                        ->where('title','like','%'.$keyword.'%')
                        ->whereOr('content','like','%'.$keyword.'%')
                        ->order('create_time desc')
                        ->page($page, 10)
                        ->all();
                }
            }
        }else{
            if ($college_id){
                $count = RequirementModel::where('status', 1)->where('college',$college_id)->count();
                if (is_mobile()){
                    $requirements = RequirementModel::with(['requirement_type', 'teacher', 'member'])
                        ->where('status', 1)
                        ->where('college',$college_id)
                        ->order('create_time desc')
                        ->all();
                }else{
                    $requirements = RequirementModel::with(['requirement_type', 'teacher', 'member'])
                        ->where('status', 1)
                        ->where('college',$college_id)
                        ->order('create_time desc')
                        ->page($page, 10)
                        ->all();
                }
            }else{
                $count = RequirementModel::where('status', 1)->count();
                if (is_mobile()){
                    $requirements = RequirementModel::with(['requirement_type', 'teacher', 'member'])
                        ->where('status', 1)
                        ->order('create_time desc')
                        ->all();
                }else{
                    $requirements = RequirementModel::with(['requirement_type', 'teacher', 'member'])
                        ->where('status', 1)
                        ->order('create_time desc')
                        ->page($page, 10)
                        ->all();
                }
            }
        }
        foreach ($requirements as $key => $vo) {
            $requirements[$key]['user'] = $vo['issuer_type'] == 0 ? $vo['teacher'] : $vo['member'];
        }
        $n_requirements = RequirementModel::where('status', 1)
            ->order('id desc')
            ->limit(0, 8)
            ->all();


        $this->assign([
            'count' => $count,
            'requirements' => $requirements,
            'page' => $page,
            'maxPage' => ceil($count / 10),
            'n_requirements' => $n_requirements,
            'keyword' => $keyword,
            'college_id' => $college_id
        ]);//,'slide'=>$slide

        if (is_mobile()){
            $this->assign('maxPage',1);
            $this->assign('page',1);
            return $this->fetch('/mobile/requirement/index');
        }

        return $this->fetch();
    }

    public function publish()
    {


        if (!session('uid')){
            return $this->error('请先登录','login/login');
        }

        $id = $this->request->param("id");
        if ($id) {
            $user = json_decode(session('userInfo'), true);
            $issuer_type = isset($user['teacher_no']) ? 0 : 1;
            $fruit = RequirementModel::where('id', $id)->find();
            $fruit['content'] = htmlspecialchars_decode($fruit['content']);
            $fruitType = RequirementTypeModel::all();
            if ($fruit && $fruit['issuer'] == $user['id'] && $fruit['issuer_type'] == $issuer_type) {
                $this->assign([
                    'requirement' => $fruit,
                    'requirement_type' => $fruitType,
                ]);
            }else{
                $this->error('无权修改','index');
            }

        } else {
            $fruitType = RequirementTypeModel::all();
            $this->assign([
                'requirement' => null,
                'requirement_type' => $fruitType,
            ]);
        }
        return $this->fetch();
    }

    public function detail()
    {
        $id = $this->request->param("id");
        if (!$id) {
            $this->redirect("index");
        } else {
            if (!session('ADMIN_ID')){
                $this->checkLogin();
            }
            $fruit = RequirementModel::where('id', $id)->find();
            $collection = null;
            if (!$fruit){
                return $this->error('需求不存在或已删除','requirement/index');
            }
            $user = json_decode(session('userInfo'),true);
            if ($user){
                $issuer_type = isset($user['teacher_no']) ? 0 : 1;
                if ($issuer_type != 0 && $user['id'] != $fruit['issuer']){
                    $this->error('无权查看');
                }
                $collection = Db::name('collection')->where('type',2)->where('cid',$id)->where('uid',$user['id'])->where('user_type',$issuer_type)->find();
            }

            $issuer = null;
            if ($fruit['issuer_type'] == 0) {
                $issuer = TeacherModel::where('id', $fruit['issuer'])->find();
            } else {
                $issuer = MemberModel::where('id', $fruit['issuer'])->find();
            }
            RequirementModel::where('id',$fruit['id'])->setInc('hits',1);
            $this->assign('collection',$collection);
            $fruit['content'] = htmlspecialchars_decode($fruit['content']);
            $this->assign('requirement', $fruit);
            $this->assign('issuer', $issuer);


                $this->assign('getList', null);

        }

        if (is_mobile()){
            return $this->fetch('/mobile/requirement/detail');

        }

        return $this->fetch();
    }


    public function adminDetail()
    {
        $id = $this->request->param("id");
        if (!$id) {
            $this->redirect("index");
        } else {
            if (!session('ADMIN_ID')){
                $this->checkLogin();
            }
            $fruit = RequirementModel::where('id', $id)->find();
            $collection = null;
            if (!$fruit){
                return $this->error('需求不存在或已删除','requirement/index');
            }
            $user = json_decode(session('userInfo'),true);
            if ($user){
                $issuer_type = isset($user['teacher_no']) ? 0 : 1;
                if ($issuer_type != 0 && $user['id'] != $fruit['issuer']){
                    $this->error('无权查看');
                }
                $collection = Db::name('collection')->where('type',2)->where('cid',$id)->where('uid',$user['id'])->where('user_type',$issuer_type)->find();
            }

            $issuer = null;
            if ($fruit['issuer_type'] == 0) {
                $issuer = TeacherModel::where('id', $fruit['issuer'])->find();
            } else {
                $issuer = MemberModel::where('id', $fruit['issuer'])->find();
            }
            RequirementModel::where('id',$fruit['id'])->setInc('hits',1);
            $this->assign('collection',$collection);
            $fruit['content'] = htmlspecialchars_decode($fruit['content']);
            $this->assign('requirement', $fruit);
            $this->assign('issuer', $issuer);
            $this->assign('isAdmin', session('ADMIN_ID'));



            if (session('ADMIN_ID')){

                $getList = Db::name('requirement_contact')->where('rid',$id)->order('id','desc')->all();

                foreach ($getList as $key => $value){
                    $user = null;
                    if ($value['user_type'] == 0){
                        $getList[$key]['user'] = TeacherModel::where('id',$value['uid'])->find();
                    }else{
                        $getList[$key]['user'] = MemberModel::where('id',$value['uid'])->find();
                    }
                }
                $this->assign('getList', $getList);

            }else{
                $this->assign('getList', null);
            }
        }

        return $this->fetch('detail');
    }


    public function save()
    {
        if ($this->request->isPost()) {
            $user = json_decode(session('userInfo'), true);
                $param = $this->request->param();

            $validate = new Requirement();
            if (!$validate->check($param)) {
                $res['code'] = 0;
                $res['msg'] = $validate->getError();
                return $res;
            }

                $id = isset($param['id']) ? $param['id'] : null;
                $param['issuer'] = $user['id'];
                $param['update_time'] = date('Y-m-d H:i:s', time());
                $param['college'] = isset($user['college']) ? $user['college'] : 0;
                $param['issuer_type'] = isset($user['teacher_no']) ? 0 : 1;
                unset($param['id']);
                $requirement = RequirementModel::where('id',$id)->find();
                if ($requirement && $requirement['issuer'] == $user['id'] && $requirement['issuer_type'] == $param['issuer_type']) {
                    $param['status'] = 0;
                    $result = RequirementModel::where('id', $id)->update($param);
                    if ($result !== false) {
                        return [
                            'code' => 1,
                            'msg' => '更新成功'
                        ];
                    } else {
                        return [
                            'code' => 0,
                            'msg' => '更新失败'
                        ];
                    }
                } else {
                    $insert = RequirementModel::insert($param);
                    if ($insert !== false) {
                        $count = get_option('requirement_count');
                        if ($count){
                            set_option('requirement_count',['count'=>( $count['count']+1)]);
                        }else{
                            set_option('requirement_count',['count'=>1]);
                        }

                        return [
                            'code' => 1,
                            'msg' => '发布成功,等待审核'
                        ];
                    } else {
                        return [
                            'code' => 0,
                            'msg' => '发布失败,请重试'
                        ];
                    }
                }
        }
    }

    public function contact(){
        if ($this->request->isPost() && $this->checkLogin()){
            $param = $this->request->param();

            $phone = $param['phone'];
            $code = $param['code'];
            $codeCheck = checkPhoneCode($phone,$code);
            if ($codeCheck === true){
                $user = json_decode(session('userInfo'), true);
                $issuer_type = isset($user['teacher_no']) ? 0 : 1;
                $data['phone'] = $phone;
                $data['rid'] = $param['id'];
                $data['uid'] = $user['id'];
                $data['user_type'] = $issuer_type;

                $check = Db::name('requirement_contact')->where($data)->find();
                $requirement = RequirementModel::where('id',$param['id'])->find();

                if ($check){
                    return [
                        'code' => 1,
                        'msg' => '获取成功1',
                        'data' => $user,
                        'requirement' => $requirement
                    ];
                }
                $data['time'] = date('Y-m-d H:i:s');

                $result = Db::name("requirement_contact")->insertGetId($data);
                if ($result !== false){
                    $requirement = RequirementModel::where('id',$param['id'])->find();
                    if ($requirement['issuer_type'] == 0){
                        $user = TeacherModel::where('id',$requirement['issuer'])->find();
                    }else{
                        $user = MemberModel::where('id',$requirement['issuer'])->find();
                    }
                    return [
                        'code' => 1,
                        'msg' => '获取成功',
                        'data' => $user,
                        'requirement' => $requirement
                    ];
                }else{
                    return [
                        'code' => 0,
                        'msg' => '验证码错误2'
                    ];
                }
            }else if ($codeCheck === -1){
                return [
                    'code' => 0,
                    'msg' => '验证码已过期'
                ];
            }else{
                return [
                    'code' => 0,
                    'msg' => '验证码错误3'
                ];
            }
        }
    }
}
